import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Response } from 'express';
import {ApiException} from "../exception/api-exception";

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
    catch(e: Object, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse<Response>();
        if(e instanceof ApiException){
            // const status = e.getStatus();
            const res = e.getResponse();
            response
                .status(200)
                .json({
                    code: res['errcode'],
                    message: res['errmsg']
                });
        }else if(e instanceof HttpException){
            // const status = e.getStatus();
            const res = e.getResponse();
            let messsage = res['message'];
            if(messsage instanceof Array){
                messsage = messsage.join(";")
            }
            response
                .status(200)
                .json({
                    code: res['statusCode'],
                    message: messsage
                });
        }else{
            console.log("服务器发生异常:",e)
            const status = 500;
            response
                .status(200)
                .json({
                    code: status,
                    message: "服务器异常"
                });
        }



    }
}